package cn.itcast.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EventLoopIOClient {

    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture channelFuture = bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler());
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                /**
                 * 注意：
                 * connect方法是异步非阻塞的方法，main线程发起了调用，但真正执行connect的是nio线程
                 */
                .connect("localhost", 8080);

        /**
         * 1.使用sync方法同步处理结果
         */
//        channelFuture.sync(); //阻塞住当前线程，直到nio线程连接建立完毕
//        Channel channel = channelFuture.channel();
//        log.debug("{}",channel);
//        channel.writeAndFlush("1111");

        /**
         * 使用 addListener 处理，将处理业务的逻辑交给nio线程，主线程就不管了
         */
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                //注意：最后执行这段逻辑的是nio线程
                Channel channel = channelFuture.channel();
                log.debug("{}",channel);
                channel.writeAndFlush("1111");
            }
        });
    }
}
